<template>
  <div class="upload">
    <div class="upload-wrapper">
      <a-upload
        list-type="picture-card"
        :file-list="fileList"
        @preview="handlePreview"
        @change="handleChange"
        :before-upload="beforeUpload"
        :action="action"
        :disabled="disabled"
        accept="image/png,image/jpeg"
      >
        <div v-if="fileList.length < 5">
          <icon name="plus" />
          <div class="ant-upload-text">
            上传
          </div>
        </div>
      </a-upload>

      <a-modal :visible="previewVisible" :footer="null" @cancel="handleCancel">
        <img alt="example" style="width: 100%" :src="previewImage" />
      </a-modal>
    </div>
    <slot name="extra">
      <div class="upload-text" v-if="text">{{ text }}</div>
    </slot>
  </div>
</template>

<script>
import { getToken } from "@/utils/auth";

function getBase64(file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result);
    reader.onerror = error => reject(error);
  });
}
export default {
  props: {
    text: {
      type: String,
      default: ""
    },
    index: {
      type: Number,
      default: 0
    },
    value: {
      type: Array,
      default: () => []
    },
    isObject: {
      type: Boolean,
      default: false
    },
    disabled: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      previewVisible: false,
      previewImage: "",
      fileList: [],
      params: {},
      edit: false
    };
  },
  watch: {
    value: {
      immediate: true,
      handler() {
        if (this.edit) {
          return;
        }

        const fileList = [];
        for (const item of this.value) {
          if (typeof item === "object") {
            this.isObject = true;
            if (item.pic) {
              item.url = item.pic;
            }

            fileList.push({
              ...item,
              uid: Math.random(),
              name: "image.png",
              status: "done"
            });
          } else {
            fileList.push({
              url: item,
              uid: Math.random(),
              name: "image.png",
              status: "done"
            });
          }
        }

        this.edit = true;
        this.fileList = fileList;
      }
    },
    fileList: {
      deep: true,
      handler(fileList) {
        const arr = [];
        for (const item of fileList) {
          if (item.status === "done") {
            let url = "";
            if (item.url) {
              url = item.url;
            } else if (item.response) {
              url =
                "https://admin.xmzhuchen.com/" + item.response.data.file.url;
            }

            if (this.isObject) {
              arr.push({
                id: item.id || 0,
                pic: url
              });
            } else {
              arr.push(url);
            }
          }
        }
        this.$emit("input", arr);
      }
    }
  },
  computed: {
    action() {
      return "https://admin.xmzhuchen.com/api/base/upload?phone=" + getToken();
    }
  },
  methods: {
    async beforeUpload(file) {
      if (!(file.type === "image/jpeg" || file.type === "image/png")) {
        this.$message.error("You can only upload JPG file!");
      }

      return true;
    },
    handleCancel() {
      this.previewVisible = false;
    },
    async handlePreview(file) {
      if (!file.url && !file.preview) {
        file.preview = await getBase64(file.originFileObj);
      }
      this.previewImage = file.url || file.preview;
      this.previewVisible = true;
    },
    handleChange({ fileList }) {
      this.edit = true;
      this.fileList = fileList;
    },
    push(item) {
      if (this.fileList.length >= 5) {
        this.$message.info("最多只能上传五张图片");

        return;
      }

      this.fileList.push({
        uid: Math.random(),
        name: "image.png",
        status: "done",
        ...item
      });
    }
  }
};
</script>

<style lang="less" scoped>
.upload-wrapper {
  display: flex;
  min-height: 112px;

  .ant-upload-text {
    text-align: center;
    color: @text-color-2;
  }

  .icon-plus {
    color: @text-color-2;
    width: 24px;
    height: 24px;
  }
}

.upload-text {
  line-height: 1.4;
  width: 112px;
  color: @text-color-2;
}
</style>
